//
//  MCFoodDetailVc.swift
//  MCBodyBuildingPro
//
//  Created by Renlvshijie on 2023/6/10.
//

import UIKit
import FSPagerView
import Kingfisher
import Toast_Swift
import AAInfographics

//食材和食物名字呼唤
class MCFoodDetailVc: MCBaseVc,FSPagerViewDataSource ,FSPagerViewDelegate{
    
    var zhName:String?
    var labels:Int?
    var ids:String?
    
    @IBOutlet weak var picVideoView: FSPagerView!{
        didSet {
            self.picVideoView.register(FSPagerViewCell.self, forCellWithReuseIdentifier: "FSPageViewCellIdentifier")
            self.picVideoView.itemSize = FSPagerView.automaticSize
        }
    }
    
    @IBOutlet weak var titleInfoLabel: UILabel!
    
    @IBOutlet weak var kcalLabel: MCPaddingLabel!
    
    @IBOutlet weak var jieshaoLabel: UILabel!
    
    @IBOutlet weak var foodIngTableView: UITableView!
    
    @IBOutlet weak var tableViewLayout: NSLayoutConstraint!
    
    
    @IBOutlet weak var PieChartView: UIView!
    
    
    @IBOutlet weak var zuofaLabel: UILabel!
    
    
    @IBOutlet weak var recommandFoodCollectionView: UICollectionView!
    
    private let foodDetailTableViewIdentifier = "foodDetailTableViewIdentifier"
    
    private let foodDetailCollectionIdentifier = "foodDetailCollectionIdentifier"
    
    private var foodIngDataSource:Array<DietActionDetailDietFoodList?> = [DietActionDetailDietFoodList?]()
    
    private var imageDataSource:Array<DietActionDetailDietDetailList?> = [DietActionDetailDietDetailList?]()
    
    private var recommandDataSource:Array<MCMcdiet?> = [MCMcdiet?]()
    
    private var pieAAChartView:AAChartView!
    
    private var pieChartModel:AAChartModel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = UIColor.qmui_color(withHexString: "#F7F7F9")
        
        self.picVideoView.automaticSlidingInterval = 3.0
        self.picVideoView.isInfinite = true
        self.picVideoView.delegate = self
        self.picVideoView.dataSource = self
        
        foodIngTableView.dataSource = self
       
        foodIngTableView.register(UINib(nibName: "MCFoodTableCell", bundle: Bundle.main), forCellReuseIdentifier: foodDetailTableViewIdentifier)
        self.foodIngTableView.rowHeight = 40
        
        let foodCollectionLayout = UICollectionViewFlowLayout.init()
        self.recommandFoodCollectionView.setCollectionViewLayout(foodCollectionLayout, animated: true)
        self.recommandFoodCollectionView.dataSource = self
        self.recommandFoodCollectionView.delegate = self
        
        self.recommandFoodCollectionView.register(UINib(nibName: "MCDietDetailCell", bundle: Bundle.main), forCellWithReuseIdentifier: foodDetailCollectionIdentifier)
        
        
        self.pieAAChartView = AAChartView.init()
        self.pieAAChartView.isScrollEnabled = false
        self.pieAAChartView.isClearBackgroundColor = true
        self.pieAAChartView.delegate = self
        self.pieAAChartView.frame = self.PieChartView.bounds
        self.PieChartView.addSubview(self.pieAAChartView)
       
       
        
        
        
        getLoadData()
        recommandList()
    }
    
    func getLoadData() {
        NetWorkRequest(MCDietApi.dietDetail(ids:ids)) { ResponseModel in
            if ResponseModel.code == 200 {
                print(ResponseModel.dataString)
                let responseModel = DietActionDetailInfoModel.init(JSONString: ResponseModel.dataString)
                self.titleInfoLabel.text = responseModel?.zhName ?? ""
                self.kcalLabel.text = "≈ \(String(describing: (responseModel?.calorie)!)) kcal"
                self.jieshaoLabel.text = responseModel?.introduce
                if responseModel?.dietFoodList?.isEmpty == false && responseModel?.dietFoodList != nil {
                    self.foodIngDataSource.append(contentsOf: responseModel?.dietFoodList ?? [])
                    self.foodIngTableView.reloadData()
                    self.tableViewLayout.constant = CGFloat(self.foodIngDataSource.count * 40)
                    
                    var foodList:Array<Any>?
                
                   foodList = self.foodIngDataSource.map { food in
                       return [food?.foodName ?? "",food?.foodWeight ?? 0] as [Any]
                    }
                    self.pieChartModel = AAChartModel()
                    self.pieChartModel.chartType(.pie)
                    self.pieChartModel.backgroundColor(UIColor.white)
                    self.pieChartModel.title("饮食结构")
                    self.pieChartModel.subtitle("饮食结构")
                    self.pieChartModel.dataLabelsEnabled(true)
                    self.pieChartModel.yAxisTitle("℃")
                    self.pieChartModel.series([
                        AASeriesElement()
                            .name("饮食结构")
                            .innerSize("80%")//内部圆环半径大小占比(内部圆环半径/扇形图半径),
                            .allowPointSelect(true)
                            .states(AAStates()
                                .hover(AAHover()
                                    .enabled(false)//禁用点击区块之后出现的半透明遮罩层
                            ))
                            .data(foodList!)
                    ])
                    self.pieAAChartView.aa_drawChartWithChartModel(self.pieChartModel)
                }
                
                self.zuofaLabel.text = responseModel?.practice ?? ""
                
                if responseModel?.dietDetailList?.isEmpty == false && responseModel?.dietDetailList != nil {
                     self.imageDataSource.append(contentsOf: responseModel?.dietDetailList ?? [])
                    self.picVideoView.reloadData()
                }
                
              
            }else {
                self.view.makeToast("网络失败",position: .center)
            }
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    func recommandList() -> Void {
        NetWorkRequest(MCDietApi.dietRecommandList(current: 1, Labels:labels, zhName:zhName)) { ResponseModel in
            if ResponseModel.code == 200 {
                let listModel = MCDietListModel(JSONString: ResponseModel.dataString)
                self.recommandDataSource.append(contentsOf: listModel?.mcdiets ?? [])
                self.recommandFoodCollectionView.reloadData()
            }else{
                self.view.makeToast("网络失败",position: .center)
            }
        } failureCallback: { ResponseModel in
            self.view.makeToast("网络失败",position: .center)
        }
    }
    
    
    func numberOfItems(in pagerView: FSPagerView) -> Int {
        return self.imageDataSource.count
    }
    
    func pagerView(_ pagerView: FSPagerView, cellForItemAt index: Int) -> FSPagerViewCell {
        let cell = pagerView.dequeueReusableCell(withReuseIdentifier: "FSPageViewCellIdentifier", at: index)
        let imageInfo = self.imageDataSource[index]
        
        cell.imageView?.kf.setImage(with: URL(string: imageInfo?.fileUrl ?? ""))
        cell.imageView?.contentMode = .scaleAspectFill
        cell.imageView?.clipsToBounds = true
      
        return cell
    }
    
    func pagerView(_ pagerView: FSPagerView, didSelectItemAt index: Int) {
        pagerView.deselectItem(at: index, animated: true)
        pagerView.scrollToItem(at: index, animated: true)
    }
     

}

extension MCFoodDetailVc:AAChartViewDelegate {
    open func aaChartViewDidFinishLoad(_ aaChartView: AAChartView) {
       print("🚀🚀🚀, AAChartView Did Finished Load!!!")
    }
    
    open func aaChartView(_ aaChartView: AAChartView, clickEventMessage: AAClickEventMessageModel) {
        print(
            """

            clicked point series element name: \(clickEventMessage.name ?? "")
            🖱🖱🖱WARNING!!!!!!!!!!!!!!!!!!!! Click Event Message !!!!!!!!!!!!!!!!!!!! WARNING🖱🖱🖱
            ==========================================================================================
            ------------------------------------------------------------------------------------------
            user finger moved over!!!,get the move over event message: {
            category = \(String(describing: clickEventMessage.category))
            index = \(String(describing: clickEventMessage.index))
            name = \(String(describing: clickEventMessage.name))
            offset = \(String(describing: clickEventMessage.offset))
            x = \(String(describing: clickEventMessage.x))
            y = \(String(describing: clickEventMessage.y))
            }
            +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
            
            
            """
        )
    }

    open func aaChartView(_ aaChartView: AAChartView, moveOverEventMessage: AAMoveOverEventMessageModel) {
        print(
            """
            selected point series element name: \(moveOverEventMessage.name ?? "")
            👌👌👌👌👌WARNING!!!!!!!!!!!!!!!!!! Touch Event Message !!!!!!!!!!!!!!!!! WARNING👌👌👌👌👌
            || ==========================================================================================
            || ------------------------------------------------------------------------------------------
            || user finger moved over!!!,get the move over event message: {
            || category = \(String(describing: moveOverEventMessage.category))
            || index = \(String(describing: moveOverEventMessage.index))
            || name = \(String(describing: moveOverEventMessage.name))
            || offset = \(String(describing: moveOverEventMessage.offset))
            || x = \(String(describing: moveOverEventMessage.x))
            || y = \(String(describing: moveOverEventMessage.y))
            || }
            || ------------------------------------------------------------------------------------------
            || ==========================================================================================
            
            
            """
        )
    }
}

extension MCFoodDetailVc:UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.foodIngDataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:MCFoodTableCell = tableView.dequeueReusableCell(withIdentifier: foodDetailTableViewIdentifier, for: indexPath) as! MCFoodTableCell
        
        let foodListModel = self.foodIngDataSource[indexPath.row]
        
        cell.letftLabel.text = foodListModel?.foodName ?? ""
        cell.centerLabel.text = "\(String(describing: (foodListModel?.foodWeight)!))g"
        cell.rightLabel.text = "≈ \(String(describing: (foodListModel?.foodCalorieStandard)!)) kcal"
        
        return cell
    }
    
    
    
}

extension MCFoodDetailVc:UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 132, height: 100)
    }
    
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 10
    }
    
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.recommandDataSource.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell:MCDietDetailCell = collectionView.dequeueReusableCell(withReuseIdentifier: foodDetailCollectionIdentifier, for: indexPath) as! MCDietDetailCell
        let dietModel = self.recommandDataSource[indexPath.row]
        cell.icImageView.kf.setImage(with: URL(string: dietModel?.previewUrl ?? ""))
        cell.titleInfoLabel.text = dietModel?.zhName
        return cell
    }
        
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let dietModel = self.recommandDataSource[indexPath.row]
        let detailVc = MCFoodDetailVc.init()
        detailVc.ids = dietModel?.id
        detailVc.zhName = dietModel?.zhName
        detailVc.labels = self.labels
        self.navigationController?.pushViewController(detailVc, animated: true)
       
    }
    
}
